<?php
# +--------------------------------------------------------
# |Description: 阳光公采接口：订单接口处理类
# +--------------------------------------------------------
# |Company: 北京申合信科技发展有限公司
# +--------------------------------------------------------
# |WebSite: www.shenhexin.com
# +--------------------------------------------------------
# |Author: Akon<18363851918@163.com>
# +--------------------------------------------------------
# |Date: 2017年6月23日
# +--------------------------------------------------------
namespace Zapi\Controller;
use Think\Controller;

class OrderController extends Controller{
    /**
     * 创建订单接口
     * URL http://api.shenhexin.com/zapi/order/createOrder?token=67a9ddb81a59f2d0611fe113effad2e8_1500255020
     * Http Method POST
     * 测试数据表：1、test_orders_jiaruiyi  2、test_orders_item_jiaruiyi
     */
    public function createOrder(){
        $receive = json_decode(file_get_contents('php://input'),true);               //接收curl post过来的数据
        $token = I('get.token');
        A('Common')->checkAccessToken($token);                                      //校验access_token

        $members = M('members','sdb_','DB_CONFIG2')->where(array('access_token'=>$token))->field('member_id,uname,name')->find();
        $_orders = $receive['addOrder'];
        $orders['order_id'] = date('YmdHis');
        $orders['ship_zip'] = $_orders['zip'];
        $orders['ship_addr'] = $_orders['provinceId'] . ' ' . $_orders['cityId'] . ' ' . $_orders['countyId'] . ' ' . $_orders['address'];
        if ($_orders['payment'] == '03' || $_orders['payment'] == '04') {
            $orders['payment'] = -1;
        } elseif ($_orders['payment'] == '09') {
            $orders['payment'] = 1;
        } else {
            $orders['payment'] = -2;
        }

        if ($_orders['invoiceState'] == '0') {
            $orders['is_tax'] = 'false';
        } elseif ($_orders['invoiceState'] == '1') {
            $orders['is_tax'] = 'true';
        }

        if ($_orders['invoiceType'] == 2) {
            $orders['invoiceType'] = 1;
        } elseif ($_orders['invoiceType'] == 6) {
            $orders['invoiceType'] = 2;
        } else {
            $orders['invoiceType'] = 1;
        }
        $cost_item = 0;
        if(!$orders['amount']){
            foreach($_orders['sku'] as $k=>$v){
                $cost_item += $v['num'] * $v['unitPrice'];
            }
        }
        $orders['tax_company'] = $_orders['invoiceTitle'];
        $orders['cost_fright'] = $_orders['servFee'];
        $orders['cost_item'] = $cost_item;
        $orders['createtime'] = time();
        $orders['acttime'] = time();
        $orders['ship_name'] = $_orders['receiverName'];
        $orders['ship_mobile'] = $_orders['mobile'];
	$orders['packageNumber'] = 'baoguoma';
        //$orders['status'] = 'active';
        if($_orders['invoiceContent'] == 1){
            $orders['tax_content'] = '明细';
        }elseif($_orders['invoiceContent'] == 3){
            $orders['tax_content'] = '电脑配件';
        }elseif($_orders['invoiceContent'] == 19){
            $orders['tax_content'] = '耗材';
        }elseif($_orders['invoiceContent'] == 22){
            $orders['tax_content'] = '办公用品';
        }
        if($_orders['remark']){
            $orders['memo'] = $_orders['remark'];
        }
        if($_orders['payment'] == '01'){
            $orders['shipping'] = '在线支付';
        }elseif($_orders['payment'] == '03'){
            $orders['shipping'] = '货到付款';
        }elseif($_orders['payment'] == '04'){
            $orders['shipping'] = '货到付款';
        }elseif($_orders['payment'] == '06'){
            $orders['shipping'] = '电汇支付';
        }
        $orders['ship_email'] = $_orders['email'];
        $orders['third_order_id'] = $_orders['tradeNo'];
        $orders['member_id'] = $members['member_id'];
        $orders['weight'] = 0.00;
        $orders['ship_time'] = '';
        $orders['tax_type'] = '';
        $orders['currency'] = 'CNY';
        $orders['pmt_amount'] = 0.00;
        $orders['gc_order_no'] = $_orders['tradeNo'];
        $orders['shipping_id'] = 11;
        $orders['ship_area'] = "mainland:" . $_orders['provinceId'] .'/'.$_orders['cityId'] . '/' . $_orders['countyId'] . '/'  .$_orders['cityId'] . ':11';
        $orders['score_e'] = $_orders['amount'];

        $skus = addApostropheToString(implode(',',getSignalValOfArr($_orders['sku'],'skuId')));
        $goods_sql = 'SELECT name,bn,price FROM sdb_goods WHERE bn IN ('."{$skus}".')';

        $goods_name = M('','','DB_CONFIG2')->query($goods_sql);

        if(!$goods_name){
            $res = array(
            'error' => '请检查输入数据是否有误'
            );
            exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
        }

        $t_orders = array();
        $orders['itemnum'] = 0;
        foreach($_orders['sku'] as $key=>$val){
            $orders['itemnum'] += $val['num'];
            $t_orders[$val['skuId']] = $val;
        }

        $product_sql = 'SELECT product_id,bn FROM sdb_products WHERE bn IN ('."{$skus}".')';
        $product_ids = M('','','DB_CONFIG2')->query($product_sql);
	
        if(!$product_ids){
            $res = array(
            'error' => '请检查输入数据是否有误'
            );
            exit(json_encode($res,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
        }

        $t_product_ids = array();
        foreach($product_ids as $k=>$v){
            $t_product_ids[$v['bn']] = $v;
        }

        $order_item = $goods_name;      //订单明细

        foreach($goods_name as $k=>$v){
            $t_goods_name[] = $v['name'] . "(" .$t_orders[$v['bn']]['num'] . ")";
            $order_item[$k]['order_id'] = $orders['order_id'];
            $order_item[$k]['amount'] = $t_orders[$v['bn']]['unitPrice'];
            $order_item[$k]['nums'] = $t_orders[$v['bn']]['num'];
            $order_item[$k]['product_id'] = $t_product_ids[$v['bn']]['product_id'];
        }
        $orders['tostr'] = implode(',',$t_goods_name);
        $orders['total_amount']= $_orders['amount'];
        $orders['final_amount'] = $_orders['amount'];

        //插入数据
        $orders_res = M('orders','sdb_','DB_CONFIG2')->add($orders);
        for($i=0;$i<count($order_item);$i++){
            $order_item_res = M('order_items','sdb_','DB_CONFIG2')->add($order_item[$i]);
        }

        $order_log = array(
            'order_id' => $orders['order_id'],
            'op_name'  => '中直商城接口',
            'log_text' => '订单创建',
            'acttime'  => time(),
            'behavior' => '添加',
            'result'   => 'success'
        );

        M('order_log','sdb_','DB_CONFIG2')->add($order_log);

        foreach($_orders['sku'] as $k=>$v){
            $return_order[$k]['skuId'] = $v['skuId'];
            $return_order[$k]['num'] = $v['num'];
            $return_order[$k]['price'] = $v['unitPrice'];
	    $return_order[$k]['orderItemId'] = '';
            $return_order[$k]['arriveData'] = date('Y-m-d',($orders['createtime']+7*24*60));
	    $return_order[$k]['packageNumber'] = 'baoguoma';
        }
        if($orders_res && $order_item_res) {
            $res = array(
                'addOrder' => array(
                    'amount' => $cost_item,
                    'freight' => $_orders['servFee'],
                    'sku' => $return_order,
                    'orderId' => $orders['order_id']
                )
            );
        }

        exit(json_encode($res));
    }

    /**
     * 取消订单接口
     * URL http://api.shenhexin.com/zapi/order/cancelOrder?token=7d64eb26b98b0afa54922f8f4ff97ce3_1500000255
     * Http Method GET
     * 1、获取接口参数access_token、order_id
     * 2、验证access_token，如果过期，则重新获取
     * 3、取消订单
     */
    public function cancelOrder(){
        $receive = json_decode(file_get_contents('php://input'),true);
        $token = I('get.token');
        A('common')->checkAccessToken($token);
	    $is_exists = M('orders','sdb_','DB_CONFIG2')->where(array('order_id'=>$receive['addConfirmOrder']['orderId']))->field('is_confirm')->find();

        if($is_exists['is_confirm'] == 0){
            $res = array(
            'error' => '订单已取消'
            );
            exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
        }
        if(count($is_exists) < 1){
            $res = array(
            'error' => '请输入正确的订单号'
            );
            exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
        }

        $info = M('orders','sdb_','DB_CONFIG2')->where(array('order_id'=>$receive['addConfirmOrder']['orderId']))->setField('is_confirm',0);
	
        if($info){
            M('orders','sdb_','DB_CONFIG2')->where(array('order_id'=>$receive['addConfirmOrder']['orderId']))->setField('cancel_time',time());
            $res = array(
                'deleteRejectOrder' => array(
                    'unCampSuccess' => 'Y'
                )
            );
        }else{
            $res = array(
                'deleteRejectOrder' => array(
                    'unCampSuccess' => 'N'
                )
            );
        }
        $this->ajaxReturn($res);
    }

    /**
     * 查询单个订单明细接口
     * 【URL】 http://api.shenhexin.com/zapi/order/getOrderDetail?token=7d64eb26b98b0afa54922f8f4ff97ce3_1500000255
     * 【Http Method】 POST
     */
    public function getOrderDetail(){
        $receive = json_decode(file_get_contents('php://input'),true);
        $token = I('get.token');
        A('Common')->checkAccessToken($token);

        $order_info = M('orders','sdb_','DB_CONFIG2')->where(array('order_id'=>$receive['getOrderDetail']['orderId']))
                                                     ->field('order_id,tax_company companyName,cost_item orderAmt,createtime,ship_mobile receiverTel,ship_addr receiverAddress,total_amount,cost_freight')
                                                     ->find();
	if(!$order_info){
	    $res = array(
		'error' => '没有数据'
	    );
	    exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_SLASHES));
	}	

        $product_sql = 'SELECT a.order_id,a.name,a.bn,a.nums,a.amount,b.brand FROM sdb_order_items a JOIN sdb_goods b ON a.bn=b.bn WHERE a.order_id = '.$order_info['order_id'];
        $product_info = M('','','DB_CONFIG2')->query($product_sql);
        $order_info['orderItemList'] = $product_info;

        $orders = array();
        foreach($order_info as $key=>$val){
            $orders['orderId'] = $order_info['order_id'];
            //$orders['companyName'] = $order_info['companyname'];
            $orders['companyName'] = '';
            $orders['orderAmt'] = $order_info['total_amount'] + $order_info['cost_fright'];
            $orders['createTime'] = date('Y-m-d H:i:s',$order_info['createtime']);
            //$orders['accountName'] = $order_info['companyname'];
            $orders['accountName'] = '';
            $orders['receiverTel'] = $order_info['receivertel'];
            $orders['receiverAddress'] = $order_info['receiveraddress'];
            foreach($order_info['orderItemList'] as $k=>$v){
                $orders['orderItemList'][$k]['orderItemId'] = '';
                $orders['orderItemList'][$k]['orderId'] = $v['order_id'];
                $orders['orderItemList'][$k]['commdtyName'] = $v['name'];
                $orders['orderItemList'][$k]['commdtyCode'] = $v['bn'];
                $orders['orderItemList'][$k]['skuNum'] = $v['nums'];
                $sql = "SELECT b.discount FROM sdb_goods a JOIN sdb_goods_cat b ON a.cat_id=b.cat_id WHERE a.bn='{$v['bn']}'";
                $discount = M('','','DB_CONFIG2')->query($sql);
                $orders['orderItemList'][$k]['unitPrice'] = sprintf('%.2f',$v['amount'] * $discount[0]['discount']);
                $orders['orderItemList'][$k]['skuAmt'] = sprintf('%.2f',$v['amount'] * $discount[0]['discount'] * $v['nums']);
                $orders['orderItemList'][$k]['brandName'] = $v['brand'];
                $orders['orderItemList'][$k]['hopeArriveTime'] = date('Y-m-d H:i:s',($order_info['createtime']+7*24*60*60));
            }
        }
        $res = array(
            'getOrderDetail' => $orders
        );
        echo json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
    }

    /**
     * 查询订单状态接口
     * 【URL】 http://api.shenhexin.com/zapi/order/getOrderStatus?token=7d64eb26b98b0afa54922f8f4ff97ce3_1500000255
     * 【Http Method】 POST
     * 付款状态
     * 0：未支付 1：已支付 2：已支付至担保方 3：部分付款 4：部分退款 5：全额退狂
     * 发货状态
     * 0：未发货 1：已发货 2：部分发货 3：部分退货 4：已退库
     */
    public function getOrderStatus(){
        $receive = json_decode(file_get_contents('php://input'),true);
        $token = I('get.token');
        A('Common')->checkAccessToken($token);

        $order_info = M('orders','sdb_','DB_CONFIG2')->where(array('order_id'=>$receive['getOrderStatus']['orderId']))->field('pay_status,ship_status')->find();

	if(empty($order_info)){
	    $res = array(
		'error' => '请确认输入的数据是否正确'
	    );
	    exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
	}

        $product_info = M('order_items','sdb_','DB_CONFIG2')->where(array('order_id'=>$receive['getOrderStatus']['orderId']))->field('bn')->select();

        $order_status = array();
        foreach($product_info as $key=>$val){
            $order_status['orderId'] = $receive['getOrderStatus']['orderId'];
            $order_status['orderStatus'] = changeOrderStatus($order_info['pay_status']);
            //$order_status['orderItemInfoList'][$key]['orderItemId'] = $receive['getOrderStatus']['orderId'];
            $order_status['orderItemInfoList'][$key]['orderItemId'] = '';
            $order_status['orderItemInfoList'][$key]['statusName'] = changeOrderStatus($order_info['pay_status']);
            $order_status['orderItemInfoList'][$key]['skuId'] = $val['bn'];
        }
        $res = array(
            'getOrderStatus' => $order_status
        );
        echo json_encode($res,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    }

    /**
     * 获取订单详情物流接口
     * 【URL】 http://api.shenhexin.com/zapi/order/getOrderLogist?token=7d64eb26b98b0afa54922f8f4ff97ce3_1500000255
     * 【Http Method】 POST
     */
    public function getOrderLogist(){
        $receive = json_decode(file_get_contents('php://input'),true);
        $token = I('get.token');
        A('Common')->checkAccessToken($token);

        $deliver_info = M('orders','sdb_','DB_CONFIG2')->where(array('order_id'=>$receive['getOrderLogist']['orderId']))->field('order_id,ship_status')->find();
	
	if(empty($deliver_info)){
	    $res = array(
		'error' => '请检查输入的数据是否正确'
	    );
	    exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
	}

        switch($deliver_info['ship_status']){
            case 0 : $operateState = '待发货';break;
            case 1 : $operateState = '已发货';break;
            case 2 : $operateState = '部分发货';break;
            case 3 : $operateState = '退货';break;
            case 4 : $operateState = '退货';break;
        }
        $res = array(
            'orderId' => $deliver_info['order_id'],
            'orderItemId' => '',
            'skuId' => $receive['getOrderLogist']['skuId'],
            'orderLogisticStatus' => array(
                'operateState' => $operateState,
                'operatorTime' => time()
            ),
	    'shippingTime' => date('Y-m-d H:i:s',time() + 24*60*60),
	    'receiveTime' => date('Y-m-d H:i:s',time() + 3*24*60*60)
        );
        echo json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
    }

    /**
     * 物流运费接口
     * 【URL】 http://api.shenhexin.com/zapi/order/getShipCarriage?token=7d64eb26b98b0afa54922f8f4ff97ce3_1500000255
     * 【Http Method】 POST
     * 注：无论客户买多少商品，运费都为0
     */
    public function getShipCarriage(){
        $receive = json_decode(file_get_contents('php://input'),true);
        $token = I('get.token');
        A('Common')->checkAccessToken($token);

        $res = array(
            'getShipCarriage' => array(
                'freightFare' => 0
            )
        );
        echo json_encode($res);
    }

    /**
     * 补开发票接口
     * 【URL】http://api.shenhexin.com/zapi/order/invoicing?token=7d64eb26b98b0afa54922f8f4ff97ce3_1500000255
     * 【Http Method】 POST
     */
    public function invoicing(){
        $receive = json_decode(file_get_contents('php://input'),true);
        if(!$receive){
            $res = array(
                'error' => '数据输入不能为空'
            );
            exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
        }
        $token = I('get.token');
        A('Common')->checkAccessToken($token);
        $order_info = $receive['confirmInvoice']['applyForInvoiceReqDTO'];

        foreach($receive['confirmInvoice']['orderInfoDTO'] as $key=>$val){
            $orderIds[$key]= $val['gcOrderNo'];
        }

        $invoice = array(
            'orderids' => implode(',',$orderIds),
            'invoice_type' => $order_info['invoiceType'],
            'consignee_name' => $order_info['consigneeName'],
            'address' =>$order_info['address'],
            'consignee_phone' => $order_info['consigneeMobileNum'],
            'tax_no' => $order_info['taxNo'],
            'reg_tel' => $order_info['regTel'],
            'reg_account' => $order_info['regAccount'],
            'reg_add' => $order_info['regAdd'],
            'company_name' => $order_info['companyName'],
            'title' => $order_info['title'],
            'invoice_content' => $order_info['invoiceContent'],
            'create_time' => time()
        );
        $res = M('invoice','sdb_','DB_CONFIG2')->add($invoice);

        $order_ids = addApostropheToString(implode(',',$orderIds));

        $sql = "SELECT a.order_id,a.third_order_id,a.ship_status,b.bn,b.name,b.price,b.amount,b.nums FROM sdb_orders a JOIN sdb_order_items b ON a.order_id=b.order_id WHERE a.order_id IN (".$order_ids.")";
        $orderItems = M('','','DB_CONFIG2')->query($sql);

        if(!$orderItems){
            $res = array(
                'error' => '请检查数据输入是否有误'
            );
            exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
        }
        //$orderItemList['sn_responseContent']['sn_body']['confirmInvoice']['allOrderItemList'] = array();
        foreach($orderItems as $key=>$val){
            $tempArr[$key]['gcOrderNo'] = $val['order_id'];
            $tempArr[$key]['orderNo'] = $val['third_order_id'];
            $tempArr[$key]['skuId'] = $val['bn'];
            $tempArr[$key]['skuName'] = $val['name'];
            $tempArr[$key]['invoiceAmount'] = $val['price'] * $val['nums'];
            $tempArr[$key]['invoiceType'] = $order_info['invoiceType'];
            $tempArr[$key]['invoiceStatus'] = 1;         //开票状态目前默认为1，即开票成功
            //0：未发货 1：已发货 2：部分发货 3：部分退货 4：已退库
            if($val['ship_status'] == 0){
                $tempArr[$key]['status'] = 2;
            }elseif($val['ship_status'] == 1){
                $tempArr[$key]['status'] = 3;
            }elseif($val['ship_status'] == 3){
                $tempArr[$key]['status'] = 3;
            }elseif($val['ship_status'] == 4){
                $tempArr[$key]['status'] = 6;
            }
        }
        $orderItemList['sn_responseContent']['sn_body']['confirmInvoice']['allOrderItemList'] = $tempArr;
        echo json_encode($orderItemList,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    }
}
